import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: null,
    // user无需特别配置，在发送请求获得用户之后将能用里面的字段
    user: {
      id: null,
      username: '',
      email: '',
      first_name: '',
      last_name: '',
      last_login: null,
      date_joined: null,
      image: null,
      birthday: null,
      location: '',
      phone: '',
      sex: 0
    }
  },
  mutations: {
    setToken (state, token) {
      // 用户登录时，设置token，并将token存储于cookies中，便于下次使用
      state.token = token
      Vue.$cookies.set('token', token)
    },
    getToken (state) {
      // 如果cookies中存在token，则从cookies中获取token
      if (Vue.$cookies.isKey('token')) {
        state.token = Vue.$cookies.get('token')
        // 获取token之后，像接口发送get请求获取对应用户信息
        Vue.axios.get('rest_auth/user/')
          .then(response => {
            console.log(response)
            this.commit('setUser', response.data)
          }).catch(error => {
            console.log(error)
          })
      } else {
        state.token = null
      }
    },
    removeToken (state) {
      // 将token设置为null，并清除cookies中的token，并将user设置成null
      state.token = null
      Vue.$cookies.remove('token')
      state.user = {
        id: null,
        username: '',
        email: '',
        first_name: '',
        last_name: '',
        last_login: null,
        date_joined: null,
        image: null,
        birthday: null,
        location: '',
        phone: '',
        sex: 0
      }
    },
    setUser (state, user) {
      state.user = user
    }
  },
  actions: {
  },
  modules: {
  }
})
